<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Program_submissions extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('wus');
		$this->load->model($this->session->userdata('formodel'));
		$this->load->library('variable');
		$this->load->library('upload');

		$config['protocol'] = "smtp";
		$config['smtp_host'] = "ssl://smtp.gmail.com";
		$config['mailpath'] = "assets/tmp";
		$config['smtp_port'] = 465;
		$config['smtp_user'] = "tetsuyakuroko101@gmail.com";
		$config['smtp_pass'] = "dwuydqsvumopnxdk";
		$config['smtp_timeout'] = 5;
		$config['charset'] = "utf-8";
		$config['mailtype'] = "html";
		$config['newline'] = "\r\n";
		$config['crlf'] = "\n";
		$this->email->initialize($config);

	}

	public function index(){
	  	$this->load->view('layouts/header',$this->variable->load_data($this->session->userdata('title')));
	  	$this->load->view($this->session->userdata('formain'),array(
	      'data' => $this->program_submissions_model->getdata2()
	    ));
	  	$this->load->view('layouts/footer');
	 }
	 
	 public function add_form(){
		$this->load->view($this->session->userdata('foradd'),array(
			'prog'		 => $this->program_submissions_model->getprograms(),
	    	'prog_type'	 => $this->program_submissions_model->getlookup('PROGRAM_TYPE'),
	    	'data_type'	 => $this->program_submissions_model->getlookup('DATATYPES'),
	    	'outtype'	 => $this->program_submissions_model->getlookup('OUTPUT_TYPES'),
	    	'outopt'	 => $this->program_submissions_model->getlookup('OUTPUT_OPTIONS'),
	    	'runtype'	 => $this->program_submissions_model->getlookup('RUN_TYPES'),
	    	'schedtype'	 => $this->program_submissions_model->getlookup('SCHED_TYPES'),

	    ));
	}

  public function edit_form($id){
		//$query = $this->program_submissions_model->editData($id);
		$this->load->view($this->session->userdata('foredit'),array(
		  'program'	     => $this->program_submissions_model->get_data($id),
		  'mods'         => $this->wus->getMod(),
		  'glLookups'    => $this->wus->getLookupValues(),
		  'modules'      => $this->wus->getModName(),
		  'modulemenu'   => $this->wus->getModuleMenus(),
		  'forms'        => $this->wus->getForms(),
		  'formfunction' => $this->wus->getFormFunctions(),
		  'prog_type'	 => $this->program_submissions_model->getlookup('PROGRAM_TYPE'),
		  'data_type'	 => $this->program_submissions_model->getlookup('DATATYPES')
	    ));
	}
	
	public function view_form($id){
		$this->load->view($this->session->userdata('forview'),array(
	      'mods'      => $this->wus->getMod(),
	      'program'	     => $this->program_submissions_model->get_data($id),
	      'modulemenu'   => $this->wus->getModuleMenus(),
	      'data_type'	 => $this->program_submissions_model->getlookup('DATATYPES'),
	      'params'		 => $this->program_submissions_model->getparams($id)
	    ));
	}

	public function searchmodmenu(){
		$query = $this->wus->getModuleMenu($this->input->post('mod_menu_id'));
		echo json_encode($query);
	}

	public function searchFormData()
	{
		$fcode = $this->input->post('form-code-s');
		$fname = $this->input->post('form-name-s');
		$mname = $this->input->post('module-name');
		$efn   = $this->input->post('exe-file-name-s');
		$query = $this->program_submissions_model->getData($fcode, $fname, $mname, $efn);
		echo json_encode($query);
	}
	
	public function save(){

		$data = array(
    		'p_program_id' 		=> $this->input->post('program_id'),
    		'p_run_type' 		=> $this->input->post('run_type'),
    		'p_param_values'	=> $this->input->post('param_values'),
    		'p_output_type'		=> $this->input->post('output_type'),
    		'p_output_option'	=> $this->input->post('output_opt'),
    		'p_sched_type' 		=> $this->input->post('sched_type'),
    		'p_interval'		=> $this->input->post('interval'),
    		'p_sched_date'	 	=> $this->input->post('sched_date'),
    		'p_user_id'			=> $this->session->userdata('user_id'),
    		'p_email'			=> $this->input->post('email'),
    		'p_trx'				=> 'I'
    	);
		//echo $data;
		$this->program_submissions_model->save_program($data); 
	}

	public function getparams(){
		echo json_encode($this->program_submissions_model->getparams($this->input->post('id')));
	}

	public function getdatus(){
		$q = $this->program_submissions_model->getdata2();
		$columns = array();
		$count = 0;
		foreach($q as $w){
			$data = array(($w->status == "CANCELED" ? '' : '<button type="button" class="btn btn-danger btn-sm"><i class="fa fa-times fa-lg"></i></button>'),$w->program_name, $w->run_type_m, $w->run_by, $w->output_type_m,'<p><span class="label '. $w->result_b.'">'. $w->result_m.'</span></p>','<p><span class="label '.$w->status_b.'">'.$w->status_m.'</span></p>', $w->output_option_m, $w->sched_type_m,$w->interval,$w->output_file);
			array_push($columns,$data);
			$count++;
		}
		echo json_encode( array('data' => $columns,'draw' => 1, "recordsTotal" => $count, "recordsFiltered" => $count ));
	}

	public function getparamsbyid(){
		echo json_encode($this->program_submissions_model->getparamsbyid($this->input->post('id')));
	}

	public function deleteparambyid(){
		echo json_encode($this->program_submissions_model->deleteparambyid($this->input->post('id')));
	}

	public function getscheds(){
		$query = $this->program_submissions_model->getscheds();
		$count = 0;
		foreach ($query as $q) {
			$this->program_submissions_model->updatestatus($q->run_id,'RUNNING',NULL,NULL);
			$folder = explode('application/views/', $q->dir_path);
			$controller = explode('.php', $q->exe_file_name);
			$dir = $folder[1];
			$values = str_replace('|', '&', $q->param_values);
			$arr = array('type='.$q->output_type, 'opt='.$q->output_option,'email='.$q->email,$values);
			$param = implode('&',$arr);
			$result = file_get_contents(site_url().$dir.'/'.$controller[0].'/gen_'.strtolower($q->output_type).'?'.$param);
			if(empty($result)){
				$this->program_submissions_model->updatestatus($q->run_id,'COMPLETED','ERROR',NULL);
			}else{
				$this->program_submissions_model->updatestatus($q->run_id,'RUNNING',NULL,$result);
				if($this->sendEmail($q->email,$result)){
					$this->program_submissions_model->updatesuccess($q->run_id);
				}else{
					$this->program_submissions_model->updatestatus($q->run_id,'COMPLETED','ERROR',NULL);
				}
				$this->program_submissions_model->updatestatus($q->run_id,'COMPLETED',NULL,NULL);
			}
			$log = fopen("logs/test_".date('YmdHiS').'_'.$count.".txt", "w") or die("Unable to open file!");
			$txt = $result;
			fwrite($log, $txt);
			fclose($log);
			$count++;
		}
	}

	public function sendEmail($email,$attachment){
 		$msg = 'test';
 		//var_dump($data);
		$this->email->from('kyogojowatersystem', $email);
		//$list = array($this->input->post('email_to'));
		$this->email->to($email);
		$this->email->subject('Kyogojo Account Registration');
		$this->email->message($msg);
		$this->email->attach($attachment);
		if ($this->email->send()) {
			//echo json_encode(array('msg' => 'success'));
			return TRUE;
		} else {
			//echo json_encode(array('msg' => 'fail'));
			return FALSE;
			//show_error($this->email->print_debugger());
		}
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */